<template>
  <div>
    <el-page-header @back="goBack"> </el-page-header>
    <div class="createCoupon">
      <el-card class="cardBox" style="min-width: 700px">
        <el-form
          :model="form"
          :rules="formRules"
          label-width="130px"
          ref="couponForm"
        >
          <el-form-item label="模板名称" prop="templateName">
            <el-input
              v-if="type === 1"
              v-model="form.templateName"
              placeholder="请输入模板名称"
              style="width: 450px"
              maxlength="30"
              show-word-limit
            ></el-input>
            <span v-else>{{ form.templateName }}</span>
          </el-form-item>
          <el-form-item label="优惠券类型" prop="couponType">
            <el-radio-group
              v-model="form.couponType"
              :disabled="type === 2 || type === 3"
              @change="couponTypeChange"
            >
              <el-radio :label="1">折扣券</el-radio>
              <el-radio :label="2">现金券</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            :label="form.couponType === 1 ? '折扣设置' : '优惠金额'"
            prop="fmtCouponAmount"
          >
            <el-input
              title=""
              v-if="type === 1"
              v-model="form.fmtCouponAmount"
              type="number"
              style="width: 450px"
              :placeholder="
                form.couponType === 1 ? '请输入折扣' : '请输入优惠金额'
              "
            >
              <template slot="append">{{
                form.couponType === 1 ? "折" : "元"
              }}</template>
            </el-input>
            <span v-else
              >{{ form.fmtCouponAmount
              }}{{ form.couponType === 1 ? "折" : "元" }}</span
            >
          </el-form-item>
          <el-form-item label="使用门槛" prop="usingLimit">
            <el-radio-group
              v-model="form.usingLimit"
              :disabled="type === 2 || type === 3"
              @change="usingLimitChange"
            >
              <el-radio :label="1">无门槛</el-radio>
              <el-radio :label="2">有门槛</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="使用门槛金额"
            prop="fmtLimitAmount"
            v-if="form.usingLimit === 2"
          >
            <el-input
              v-if="type === 1"
              v-model="form.fmtLimitAmount"
              type="number"
              style="width: 450px"
              placeholder="请输入使用门槛金额"
              :step="0.01"
              oninput="if(isNaN(value)) { value = parseFloat(value) } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
            >
              <template slot="append">元</template>
            </el-input>
            <span v-else>{{ form.fmtLimitAmount }}元</span>
          </el-form-item>
          <el-form-item label="有效期" prop="expiresType">
            <el-radio-group
              v-model="form.expiresType"
              :disabled="type === 2 || type === 3"
              @change="expiresTypeChange"
            >
              <el-radio :label="1">固定时间</el-radio>
              <el-radio :label="2">用户领取后有效天数</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="固定时间"
            v-if="form.expiresType === 1"
            prop="expiresDate"
          >
            <el-date-picker
              v-model="form.expiresDate"
              :disabled="type === 2 || type === 3"
              style="width: 450px"
              type="datetimerange"
              range-separator="至"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="有效天数"
            v-if="form.expiresType === 2"
            prop="expiresDay"
          >
            <el-input
              v-if="type === 1"
              style="width: 450px"
              placeholder="请输入有效天数"
              v-model="form.expiresDay"
            >
              <template slot="append">天</template>
            </el-input>
            <span v-else>{{ form.expiresDay }}天</span>
          </el-form-item>
          <el-form-item label="优惠券数量" prop="couponNum">
            <el-input
              v-if="type === 1"
              v-model.number="form.couponNum"
              placeholder="请输入优惠券数量"
              style="width: 450px"
              type="number"
            ></el-input>
            <span v-else>{{ form.couponNum }}</span>
          </el-form-item>
          <el-form-item label="已发放数量" v-if="id">
            <span>{{ form.issueCouponNum }}</span>
          </el-form-item>
          <el-form-item label="退款后是否退券" prop="refundType">
            <el-radio-group
              v-model="form.refundType"
              :disabled="type === 2 || type === 3"
            >
              <el-radio :label="1">退还</el-radio>
              <el-radio :label="2">不退还</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" style="margin-top: 50px" v-if="type === 1">
            <el-button class="width120" @click="goBack">取消</el-button>
            <el-button class="width120" type="primary" @click="submit"
              >提交</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
      <el-card
        class="cardBox"
        style="margin-left: 20px; min-width: 700px"
        v-if="type === 2"
      >
        <el-form :model="form" label-width="120px">
          <el-form-item label="发放方式">
            <el-radio-group v-model="issuedType">
              <el-radio label="1" value>直接输入</el-radio>
              <el-radio label="2">导入文件</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="issuedType === '1'">
            <el-input
              type="textarea"
              :rows="6"
              placeholder="请输入用户ID，以逗号隔开，最多输入100条"
              v-model="accountId"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="" v-if="issuedType === '2'">
            <el-upload
              class="upload-demo"
              action="/merchantApi/oss/upload"
              :headers="{
                auth_token: getToken(),
                auth_tmp: curTmp,
                auth_tck: curTck,
              }"
              :file-list="fileList"
              :before-upload="handleBefore"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
            >
              <el-button style="width: 287px">上传文件</el-button>
              <div slot="tip" class="el-upload__tip" style="color: #bfbfbf">
                支持的文件格式：csv、txt。每行一个用户
                ID（8-30位字符串，不允许中文），每个文件最多支持 100 行
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="" style="margin-top: 50px">
            <el-button class="width120" @click="goBack">取消</el-button>
            <el-button class="width120" type="primary" @click="handleProvide"
              >确认发放</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
      <el-card
        class="cardBox"
        style="margin-left: 20px; min-width: 700px"
        v-if="type === 3"
      >
        <div style="margin-bottom: 10px; color: #869daa">已发放优惠券列表</div>
        <el-table :height="fixedTableHeight" :data="dataList">
          <template slot="empty">
            <el-empty
              :image="require('@/assets/imgs/middleWork/k1.png')"
              :image-size="80"
              description="暂无相关数据"
            ></el-empty>
          </template>
          <el-table-column
            show-overflow-tooltip
            prop="id"
            align="center"
            label="优惠券ID"
          >
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="accountId"
            align="center"
            label="用户ID"
          >
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="gmtCreated"
            align="center"
            label="发放时间"
          >
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="status"
            align="center"
            label="状态"
          >
            <template slot-scope="scope">
              {{
                scope.row.status === 1
                  ? "有效"
                  : scope.row.status === 2
                  ? "过期"
                  : scope.row.status === 3
                  ? "已用"
                  : ""
              }}
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          layout="prev, pager, next, sizes, jumper"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          :current-page="1"
          :total="total"
          @current-change="pageCurrentChangeHandle"
          @size-change="pageSizeChangeHandle"
        >
        </el-pagination>
      </el-card>
    </div>
  </div>
</template>

<script>
import mixin from "@/mixins/mixin";
import { isNumber, isAmount, isCoupon,isCnEnNum } from "@/utils/validate";
import { getToken } from "@/utils/public";
import { mapMutations } from "vuex";
import crypto from "@/crypto";
import { randomWord } from "@/utils/getRandom";

export default {
  mixins: [mixin],
  name: "createCoupon",
  data() {
    const testAccName = (rule, value, callback) => {
      if (isCnEnNum(value)) {
        callback();
      } else {
        callback(new Error("请输入中/英文数字，不支持特殊字符"));
      }
    };
    const checkLimitAmount = (rule, value, callback) => {
      if (this.form.usingLimit === 1) {
        callback();
      }
      if (value == null) {
        callback(new Error("请输入门槛金额"));
      }
      if (1000000 >= value && value > 0) {
        if (!isAmount(value)) {
          callback(new Error("门槛金额最多保留两位小数"));
        }
        callback();
      } else {
        callback(new Error("门槛金额必须大于0且小于等于1000000"));
      }
      // if (value > 0) {
      //   if (!isAmount(value)) {
      //     callback(new Error("门槛金额最多保留两位小数"));
      //   }
      //   callback();
      // } else {
      //   callback(new Error("门槛金额必须大于0"));
      // }
    };
    const checkExpiresDay = (rule, value, callback) => {
      if (this.form.expiresType === 1) {
        callback();
      }
      if (value > 0 && value < 366) {
        if (!isNumber(value)) {
          callback(new Error("有效天数必须为整数"));
        }
        callback();
      } else {
        callback(new Error("有效天数必须大于0小于等于365"));
      }
    };
    const checkCouponAmount = (rule, value, callback) => {
      if (this.form.couponType === 1) {
        //折扣
        if (value == null) {
          callback(new Error("请输入折扣"));
        }
        if (value < 10 && value > 0) {
          if (!isCoupon(value)) {
            callback(new Error("折扣设置最多保留一位小数"));
          }
          callback();
        } else {
          callback(new Error("折扣设置必须大于0小于10"));
        }
      } else {
        //固定金额
        if (value == null) {
          callback(new Error("请输入优惠金额"));
        }
        if (1000000 >= value && value > 0) {
          if (!isAmount(value)) {
            callback(new Error("优惠金额最多保留两位小数"));
          }
          callback();
        } else {
          callback(new Error("优惠金额必须大于0且小于等于1000000"));
        }
      }
    };
    const checkCouponNum = (rule, value, callback) => {
      if (1000000 >= value && value > 0) {
        if (!isNumber(value)) {
          callback(new Error("优惠券数量必须为整数"));
        }
        callback();
      } else {
        callback(new Error("优惠券数量必须大于0且小于等于1000000"));
      }
    };
    const checkExpiresDate = (rule, value, callback) => {
      if (this.form.expiresType === 2) {
        callback();
      }
      var nowDate = new Date();
      var now = nowDate.valueOf();
      var start = new Date(value[0]).valueOf();
      var end = new Date(value[1]).valueOf();
      if (end <= now) {
        callback(new Error("结束时间必须大于当前时间"));
      } else {
        if (start >= end) {
          callback(new Error("结束时间必须大于起始时间"));
        } else {
          callback();
        }
      }
    };
    return {
      mixinViewModuleOptions: {
        getDataListURL: "/api/merchant/couponIssued/searchByPage",
        createdIsNeed: false,
      },
      form: {
        couponType: 1,
        usingLimit: 1,
        expiresType: 1,
        fmtCouponAmount: "",
        refundType: 1,
        fmtLimitAmount: null,
        expiresDay: "",
        expiresDate: null,
      },
      dataForm: {},
      curTmp: null,
      curTck: null,
      len: [8, 9, 10, 11, 12][
        Math.floor(Math.random() * [8, 9, 10, 11, 12].length)
      ],
      dataList: [],
      id: null,
      fileList: [],
      issuedType: "1", // 发放方式
      accountId: "", // 批量发放编号
      type: 1, // 1--仅创建， 2--发放
      formRules: {
        templateName: [
          { required: true, message: "请输入模板名称", trigger: "change" },
          {
            validator: testAccName,
            trigger: "change",
          },
          { max: 30, message: "最大长度30字符", trigger: "change" },
          { min: 5, message: "最小长度5字符", trigger: "change" },
        ],
        couponType: [
          { required: true, message: "请选择优惠券类型", trigger: "change" },
        ],
        fmtCouponAmount: [
          { required: true, message: "请输入折扣设置", trigger: "change" },
          { validator: checkCouponAmount, trigger: "change" },
        ],
        usingLimit: [
          { required: true, message: "请选择使用门槛", trigger: "change" },
        ],
        fmtLimitAmount: [
          { required: false, message: "请输入使用门槛金额", trigger: "change" },
          { validator: checkLimitAmount, trigger: "change" },
        ],
        expiresType: [
          { required: true, message: "请选择有效期", trigger: "change" },
        ],
        expiresDate: [
          { required: true, message: "请选择固定时间", trigger: "change" },
          { validator: checkExpiresDate, trigger: "change" },
        ],
        expiresDay: [
          { required: false, message: "请输入有效天数", trigger: "change" },
          { validator: checkExpiresDay, trigger: "change" },
        ],
        couponNum: [
          { required: true, message: "请输入优惠券数量", trigger: "change" },
          { validator: checkCouponNum, trigger: "change" },
        ],
        refundType: [
          {
            required: true,
            message: "请选择退款后是否退券",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.curTmp = new Date().getTime();
    this.curTck = crypto.set(
      getToken() + "_" + this.curTmp + "_" + randomWord(this.len),
      "a1g0qoalvv19aed3"
    );

    this.type = +this.$route.query.type;
    this.id = this.$route.query.id;
    if (this.type === 3 || this.type === 2) {
      this.formRules = {};
    }
    if (this.type === 3) {
      this.dataForm.templateId = this.id;
      this.getDataList();
    }
    if (this.id) {
      this.$http
        .get(`/api/merchant/couponTemplate/get`, {
          params: { id: this.id },
        })
        .then((res) => {
          if (res.code === "0000") {
            this.form = res.data;
            if (this.form.expiresType === 1) {
              this.form.expiresDate = [
                this.form.expiresStart + ":00",
                this.form.expiresEnd + ":00",
              ];
            }
          }
        });
    }
  },
  watch: {
    "$store.state.testLine": {
      handler() {
        if (this.$route.name == this.$options.name) {
          if (this.type != "1") {
            this.testCancel();
            // this.$router.push("/marketingTool/coupon");
          }
        }
      },
    },
    deep: true,
  },
  methods: {
    ...mapMutations(["changeLive"]),
    getToken,
    
    couponTypeChange(val) {
      this.form.fmtCouponAmount = null;
      this.$refs.couponForm.clearValidate("fmtCouponAmount");
      if (val === 1) {
        this.formRules.fmtCouponAmount[0].message = "请输入折扣设置";
      } else {
        this.formRules.fmtCouponAmount[0].message = "请输入优惠金额";
      }
    },
    expiresTypeChange(val) {
      setTimeout(() => {
        this.$refs.couponForm.clearValidate(["expiresDate", "expiresDay"]);
      }, 0);
      if (val === 1) {
        this.form.expiresDay = null;
        this.formRules.expiresDay[0].required = false;
        this.formRules.expiresDate[0].required = true;
      } else {
        this.form.expiresDate = null;
        this.formRules.expiresDay[0].required = true;
        this.formRules.expiresDate[0].required = false;
      }
    },
    usingLimitChange(val) {
      this.form.fmtLimitAmount = null;
      this.$refs.couponForm.clearValidate(["fmtLimitAmount"]);
      if (val === 1) {
        this.formRules.fmtLimitAmount[0].required = false;
      } else {
        this.formRules.fmtLimitAmount[0].required = true;
      }
    },
    goBack() {
      this.testCancel();
      this.$backTo(`/marketingTool/coupon`);
    },
    submit() {
      this.$refs.couponForm.validate((valid) => {
        if (valid) {
          if (this.form.expiresType === 1) {
            this.form.expiresStart = this.$moment(
              this.form.expiresDate[0]
            ).format("YYYY-MM-DD HH:mm:ss");
            this.form.expiresEnd = this.$moment(
              this.form.expiresDate[1]
            ).format("YYYY-MM-DD HH:mm:ss");
          }
          if (this.id) {
            this.$http
              .put("/api/merchant/couponTemplate/edit", this.form)
              .then((res) => {
                if (res.code === "0000") {
                  this.$message.success("编辑成功！");
                  this.testCancel();
                  // this.goBack();
                }
              });
          } else {
            this.$http
              .post("/api/merchant/couponTemplate/add", this.form)
              .then((res) => {
                if (res.code === "0000") {
                  this.$message.success("新建成功！");
                  this.testCancel();
                  // this.goBack();
                }
              });
          }
        }
      });
    },
    handleRemove() {
      this.fileList = [];
    },
    handleSuccess(res, file) {
      this.fileList = [];
      this.fileList = [file.raw];
    },
    handleBefore(file) {
      const is2M = file.size / 1024 / 1024 < 2;
      if (!file.name.includes("txt") && !file.name.includes("csv")) {
        this.$message.warning("只支持csv、txt格式");
        return false;
      }
      if (!is2M) {
        this.$message.warning("上传文件大小不能超过2M");
        return false;
      }
      return true;
    },
    getDetail() {
      if (this.id) {
        this.$http
          .get(`/api/merchant/couponTemplate/get`, {
            params: { id: this.id },
          })
          .then((res) => {
            if (res.code === "0000") {
              this.form = res.data;
              if (this.form.expiresType === 1) {
                this.form.expiresDate = [
                  this.form.expiresStart + ":00",
                  this.form.expiresEnd + ":00",
                ];
              }
            }
          });
      }
    },
    handleProvide() {
      if (!this.issuedType) {
        return this.$message.warning("请选择发放方式！");
      }
      if (this.issuedType === "1") {
        if (this.accountId.length === 0) {
          return this.$message.warning("请输入用户id");
        }
        this.$http
          .post("/api/merchant/couponIssued/add", {
            templateId: this.id,
            issuedType: this.issuedType,
            accountId: this.accountId,
          })
          .then((res) => {
            if (res.code === "0000") {
              this.$message.success("发放成功！");
              this.testCancel();
              // this.getDetail();
            }
          });
      } else {
        const formData = new FormData();
        if (this.fileList.length === 0) {
          return this.$message.warning("请上传文件");
        }
        formData.append("file", this.fileList[0]);
        this.$http
          .post("/api/merchant/couponIssued/upload", formData, {
            params: {
              templateId: this.id,
              issuedType: this.issuedType,
            },
          })
          .then((res) => {
            if (res.code === "0000") {
              this.$message.success("发放成功！");
              this.testCancel();
              // this.getDetail();
            }
          });
      }
    },
    testCancel() {
      this.$store.commit("changeLive", false);
      setTimeout(() => {
        this.$store.commit("changeLive", true);
      }, 0);
      this.$backTo("/marketingTool/coupon");
    },
  },
};
</script>

<style lang="scss" scoped>
.createCoupon {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  .cardBox {
    flex: 1;
    padding: 60px 50px;
    // height: 80vh;
  }
  :deep(.el-form-item__label) {
    color: #869daa;
  }
  :deep(
      input[type="number"]::-webkit-inner-spin-button,
      input[type="number"]::-webkit-outer-spin-button
    ) {
    -webkit-appearance: none;
    margin: 0;
  }
}
</style>
